package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type jsonIn struct {
	Head string           `json:head`
	Body *json.RawMessage `json:body`
}

func newJsonIn() *jsonIn {
	return &jsonIn{
		Body: &json.RawMessage{},
	}
}

//interface{}类型的json格式的编码和解码
func InterfaceEnDecoder() {
	fmt.Printf("\n Example of InterfaceEnDecoder ")
	dec := json.NewDecoder(os.Stdin)
	enc := json.NewEncoder(os.Stdout)
	for {
		var v map[string]interface{}
		if err := dec.Decode(&v); err != nil {
			fmt.Println("err - Decode:", err.Error())
			return
		}
		if err := enc.Encode(&v); err != nil {
			fmt.Println("err - Encode:", err.Error())
		}
	}
}

//结构体类型的json格式的编码和解码
func StructEnDecoder() {
	fmt.Printf("\n Example of StructEnDecoder ")
	dec := json.NewDecoder(os.Stdin)
	enc := json.NewEncoder(os.Stdout)
	for {
		v := newJsonIn()
		if err := dec.Decode(&v); err != nil {
			fmt.Println("err - Decode:", err.Error())
			return
		}
		fmt.Println("v1:", v)
		if err := enc.Encode(&v); err != nil {
			fmt.Println("err - Encode:", err.Error())
		}
	}
}

func main() {
	StructEnDecoder()
	InterfaceEnDecoder()
}
